﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BLL;
using DLL;
using System.Windows.Forms;
using CommonHelpers;
using Logging;

namespace QuanLyBanLe
{
    public partial class FormOrder
    {
        private ReturnProductService m_returnProductService;
        private List<pSellProducts_Result> m_SellProducts;
        private bool m_ReturnProductEnableEvent;

        private void InitReturnProductMan() 
        {
            m_returnProductService = new BLL.ReturnProductService();
            m_ReturnProductEnableEvent = false;
        }

        private void LoadReturnProductMan()
        {
            GetSellProducts();

            colProducer3.DataSource = m_Producers;
            colProducer3.ValueMember = "Id";
            colProducer3.DisplayMember = "Name";

            colProductType3.DataSource = m_ProductTypes;
            colProductType3.ValueMember = "Id";
            colProductType3.DisplayMember = "Name";

            colProduct3.DataSource = m_Products;
            colProduct3.ValueMember = "Id";
            colProduct3.DisplayMember = "Name";

            lblTotalReturnProductPrice.Text = "0 Đ";
            m_ReturnProductEnableEvent = true;
        }

        private void GetSellProducts()
        {
            m_SellProducts = m_ProductService.GetProductsAndSellAmount();
            pSellProducts_Result allProduct = new pSellProducts_Result();
            allProduct.Id = 0;
            allProduct.Name = "Tất cả";
            allProduct.SellAmount = 0;
            m_SellProducts.Insert(0, allProduct);
        }

        private void ReturnProductReset()
        {
            lblTotalReturnProductPrice.Text = "0 Đ";
            txtComment.Text = "";
            dtgReturnProducts.DataSource = null;
            dtgReturnProducts.Rows.Clear();
        }

        private bool SaveReturnProduct()
        {
            bool result = false;
            try
            {
                ReturnProduct returnProduct = new ReturnProduct
                {
                    ReturnDate = dtpReturnDate.Value,
                    Comment = txtComment.Text
                };
                List<ReturnProductDetail> details = new List<ReturnProductDetail>();
                foreach (DataGridViewRow row in dtgReturnProducts.Rows)
                {
                    if (!row.IsNewRow)
                    {
                        ReturnProductDetail detail = new ReturnProductDetail();
                        detail.ProductId = Convert.ToInt32(row.Cells["colProduct3"].Value);
                        detail.Amount = Convert.ToInt32(row.Cells["colAmountReturn3"].Value);
                        if (detail.ProductId > 0 && detail.Amount > 0)
                        {
                            details.Add(detail);
                        }
                    }
                }
                if (details.Count > 0)
                {
                    result = m_returnProductService.AddReturnProduct(returnProduct, details);
                    GetSellProducts();
                }
            }
            catch (Exception ex)
            {
                result = false;
                MyLogger.LogException("Lỗi xảy ra khi tra hàng: " + ex.Message, ex);
            }
            return result;
        }

        private bool IsProductAddedToReturnProducts(int productId)
        {
            bool isExisted = false;
            for (int i = 0; i < dtgReturnProducts.Rows.Count; i++)
            {
                int returnProductId = Convert.ToInt32(dtgReturnProducts.Rows[i].Cells["colProduct3"].Value);
                if (returnProductId == productId)
                {
                    isExisted = true;
                    break;
                }
            }
            return isExisted;
        }

        private void CalculateTotalReturnProductPrice()
        {
            int totalPrice = 0;
            foreach (DataGridViewRow row in this.dtgReturnProducts.Rows)
            {
                var temp = row.Cells["colTotalPrice3"].Value;
                if (temp != null)
                {
                    int itemPrice = 0;
                    if (int.TryParse(temp.ToString(), out itemPrice))
                    {
                        totalPrice += itemPrice;
                    }
                }
            }

            lblTotalReturnProductPrice.Text = totalPrice.ToMoney();
        }

        private void ReturnProductEnableControls(bool enable)
        {
            dtgReturnProducts.ReadOnly = !enable;
            txtComment.Enabled = enable;
            dtpReturnDate.Enabled = enable;
            btnReturnProductSave.Enabled = enable;
        }

        private void dtgReturnProducts_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == dtgReturnProducts.Columns["colDelete3"].Index)
            {
                DialogResult result = MessageBox.Show("Bạn có chắc muốn xóa chi tiết trả hàng này", "Thông báo",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    dtgReturnProducts.Rows.RemoveAt(e.RowIndex);
                    CalculateTotalReturnProductPrice();
                }
            }
        }

        private void dtgReturnProducts_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                return;
            }
            var currentRow = dtgReturnProducts.Rows[e.RowIndex];
            if (e.ColumnIndex == currentRow.Cells["colAmountReturn3"].ColumnIndex ||
                e.ColumnIndex == currentRow.Cells["colSalePrice3"].ColumnIndex)
            {
                int salePrice = Convert.ToInt32(currentRow.Cells["colSalePrice3"].Value);
                int amount = Convert.ToInt32(currentRow.Cells["colAmountReturn3"].Value);
                int totalPrice = salePrice * amount;
                currentRow.Cells["colTotalPrice3"].Value = totalPrice;
                CalculateTotalReturnProductPrice();
            }
        }

        private void dtgReturnProducts_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            var currentRow = dtgReturnProducts.Rows[e.RowIndex];
            if (currentRow.IsNewRow) { return; }

            currentRow.ErrorText = "";
            bool isValid = true;

            // validate return amount
            if (e.ColumnIndex == dtgReturnProducts.Columns["colAmountReturn3"].Index)
            {
                if (e.FormattedValue == null)
                {
                    isValid = false;
                    currentRow.ErrorText = "Nhập số lượng trả";
                }
                else
                {
                    int amount;
                    bool parseSuccess = int.TryParse(e.FormattedValue.ToString(), out amount);
                    if (parseSuccess)
                    {
                        if (amount <= 0)
                        {
                            isValid = false;
                            currentRow.ErrorText = "Sai số lượng";
                        }
                        else
                        {
                            int maxAmount = Convert.ToInt32(currentRow.Cells["colMaxAmount"].Value);
                            if (amount > maxAmount)
                            {
                                isValid = false;
                                currentRow.ErrorText = "Số lượng trả phải nhỏ hơn hoặc bằng số lượng đã mua";
                            }
                        }
                    }
                    else
                    {
                        isValid = false;
                        currentRow.ErrorText = "Sai số lượng";
                    }
                }
            }

            e.Cancel = !isValid;
        }

        private void btnReturnProductSave_Click(object sender, EventArgs e)
        {
            try
            {
                bool success = SaveReturnProduct();
                if (success)
                {
                    MessageBox.Show("Đã trả hàng", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ReturnProductEnableControls(false);
                }
                else
                {
                    MessageBox.Show("Có lổi xảy ra, không trả hàng thành công, vui lòng kiểm tra lại số lượng", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                if (ex.InnerException != null)
                {
                    MessageBox.Show(ex.InnerException.Message);
                }
            }
        }

        private void btnNewReturnProduct_Click(object sender, EventArgs e)
        {
            ReturnProductReset();
            ReturnProductEnableControls(true);
        }

        private void dtgReturnProducts_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (e.Control is ComboBox)
            {
                int currentColumnIndex = dtgReturnProducts.CurrentCell.ColumnIndex;
                ComboBox cbo = e.Control as ComboBox;
                SetupAutoCompleteDropdownInGrid(cbo);
                if (currentColumnIndex == dtgReturnProducts.Columns["colProduct3"].Index)
                {
                    // To avoid register twice, remove handler before register
                    cbo.SelectedIndexChanged -= new EventHandler(m_cboProduct3_SelectedIndexChanged);
                    cbo.SelectedIndexChanged += new EventHandler(m_cboProduct3_SelectedIndexChanged);
                }
            }

            if (dtgReturnProducts.CurrentCell.ColumnIndex == dtgReturnProducts.Columns["colAmountReturn3"].Index)
            {
                TextBox item = e.Control as TextBox;
                if (item != null)
                {
                    item.KeyPress += new KeyPressEventHandler(item_KeyPress);
                }
            }
        }

        private void m_cboProduct3_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox cbo = sender as ComboBox;
            if (m_ReturnProductEnableEvent && dtgReturnProducts.CurrentCell != null
                && cbo.SelectedIndex > -1 && cbo.SelectedValue is int //Combobox should complete
                && dtgReturnProducts.CurrentCell.ColumnIndex == dtgReturnProducts.Columns["colProduct3"].Index)
            {
                // Set value for current row
                int productId = Convert.ToInt32(cbo.SelectedValue);
                if (productId != 0)
                {
                    if (IsProductAddedToReturnProducts(productId))
                    {
                        MessageBox.Show("Sản phẩm đã được thêm vào danh sách trả hàng", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        m_ReturnProductEnableEvent = false;
                        cbo.SelectedValue = 0;
                        m_ReturnProductEnableEvent = true;
                    }
                    else
                    {
                        pSellProducts_Result product = m_SellProducts.Where(x => x.Id == productId).FirstOrDefault();
                        if (product.SellAmount > 0)
                        {
                            dtgReturnProducts.CurrentRow.Cells["colProductType3"].Value = product.ProductTypeId;
                            dtgReturnProducts.CurrentRow.Cells["colProducer3"].Value = product.ProducerId;
                            dtgReturnProducts.CurrentRow.Cells["colProduct3"].Value = product.Id;
                            dtgReturnProducts.CurrentRow.Cells["colMaxAmount"].Value = product.SellAmount;
                            dtgReturnProducts.CurrentRow.Cells["colSalePrice3"].Value = product.SalePrice;
                            dtgReturnProducts.CurrentRow.Cells["colAmountReturn3"].Value = 1;
                            dtgReturnProducts.CurrentRow.Cells["colTotalPrice3"].Value = product.SalePrice;
                        }
                        else
                        {
                            MessageBox.Show("Sản phẩm chưa bán nên không thể trả hàng", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            m_ReturnProductEnableEvent = false;
                            cbo.SelectedValue = 0;
                            m_ReturnProductEnableEvent = true;
                        }
                    }
                }
                else // User choose "Tat ca" product, then reset all columns' value
                {
                    dtgReturnProducts.CurrentRow.Cells["colMaxAmount"].Value = null;
                    dtgReturnProducts.CurrentRow.Cells["colSalePrice3"].Value = null;
                    dtgReturnProducts.CurrentRow.Cells["colAmountReturn3"].Value = null;
                    dtgReturnProducts.CurrentRow.Cells["colTotalPrice3"].Value = null;
                }
            }
        }

        private void dtgReturnProducts_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            // set defaut value for dropdown columns in grid
            e.Row.Cells["colProductType3"].Value = 0;
            e.Row.Cells["colProducer3"].Value = 0;
            e.Row.Cells["colProduct3"].Value = 0;
        }

        private void dtgReturnProducts_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            // Filter products by product type and producer
            if (e.ColumnIndex == dtgReturnProducts.Columns["colProduct3"].Index)
            {
                var cellProductType = dtgReturnProducts.Rows[e.RowIndex].Cells["colProductType3"];
                var cellProducer = dtgReturnProducts.Rows[e.RowIndex].Cells["colProducer3"];
                if (cellProductType.Value != null && cellProducer.Value != null)
                {
                    int productTypeId = Convert.ToInt32(cellProductType.Value);
                    int producerId = Convert.ToInt32(cellProducer.Value);
                    if (productTypeId != 0 || producerId != 0)
                    {
                        List<pSellProducts_Result> products = m_SellProducts.Where(x => (productTypeId == 0 || x.ProductTypeId == productTypeId) &&
                                                                                        (producerId == 0 || x.ProducerId == producerId)).ToList();
                        pSellProducts_Result allProduct = new pSellProducts_Result();
                        allProduct.Id = 0;
                        allProduct.Name = "Tất cả";
                        allProduct.SellAmount = 0;
                        products.Insert(0, allProduct);
                        DataGridViewComboBoxCell cellProduct = (DataGridViewComboBoxCell)dtgReturnProducts[e.ColumnIndex, e.RowIndex];
                        cellProduct.DataSource = products;
                        cellProduct.ValueMember = "Id";
                        cellProduct.DisplayMember = "Name";

                        // reset value of product column if product type or producer is changed, so the old product is not belong to new colllection of new products
                        var existingProduct = products.Where(p => p.Id == Convert.ToInt32(cellProduct.Value)).FirstOrDefault();
                        if (existingProduct == null)
                        {
                            cellProduct.Value = 0; // reset to "all product"
                        }
                    }
                    else
                    {
                        DataGridViewComboBoxCell cellProduct = (DataGridViewComboBoxCell)dtgReturnProducts[e.ColumnIndex, e.RowIndex];
                        cellProduct.DataSource = m_SellProducts;
                        cellProduct.ValueMember = "Id";
                        cellProduct.DisplayMember = "Name";
                    }
                }
            }
        }

        private void dtgReturnProducts_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (dtgReturnProducts.Rows[e.RowIndex].Cells["colRowNumber3"].Value == null ||
                dtgReturnProducts.Rows[e.RowIndex].Cells["colRowNumber3"].Value == DBNull.Value)
            {
                dtgReturnProducts.Rows[e.RowIndex].Cells["colRowNumber3"].Value = e.RowIndex + 1;
            }
        }

        private void dtgReturnProducts_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (dtgReturnProducts.IsCurrentCellDirty)
            {
                int productId = Convert.ToInt32(dtgReturnProducts.CurrentRow.Cells["colProduct3"].Value);
                if (productId > 0)
                {
                    dtgReturnProducts.CommitEdit(DataGridViewDataErrorContexts.Commit);
                }
            }
        }     
    }
}
